﻿using System.Collections.Generic;
using System.Threading.Tasks;

namespace Odyssey.Consul.Implementations
{
    using Features;
    using Http;
    using Models;
    public class Coordinate : BaseConsulAPI, ICoordinate
    {
        public Coordinate(IHttpRequester httpRequester, IConsulConfiguration consulConfiguration) : base(httpRequester, consulConfiguration, EnumResource.Node)
        {

        }
         
        private string BuildCoordinatePath(string action = "")
        {
            return BuildUri("coordinate", action);
        }

        private QueryParameter BuidQueryParameter(ArguCoordinate arguCoordinate)
        {
            QueryParameter queryParameter = null;
            if (arguCoordinate != null)
            {
                queryParameter = new QueryParameter();
                if (!string.IsNullOrWhiteSpace(arguCoordinate.DC))
                {
                    queryParameter.Datacenter = arguCoordinate.DC;
                }
                if (!string.IsNullOrWhiteSpace(arguCoordinate.Segment))
                {
                    queryParameter.OtherParameters.Add("segment", arguCoordinate.Segment);
                }
            }
            return queryParameter;
        }

        public async Task<List<ResultCoordinate>> ReadLanCoordinateForAllNode(ArguCoordinate arguCoordinate)
        {
            return await ApiSend<List<ResultCoordinate>>(BuildCoordinatePath("nodes"), queryParameter: BuidQueryParameter(arguCoordinate));
        }

        public async Task<List<ResultCoordinate>> ReadLanCoordinateForNode(ArguCoordinate arguCoordinate)
        {
            var path = BuildCoordinatePath($"node/{arguCoordinate.Node}");
            return await ApiSend<List<ResultCoordinate>>(path, queryParameter: BuidQueryParameter(arguCoordinate));
        }

        public async Task<List<ResultCoordinate>> ReadWanCoordinate()
        {
            return await ApiSend<List<ResultCoordinate>>(BuildCoordinatePath("datacenters"));
        }

        public async Task UpdateLanCoordinateForNode(ArguUpdateLanCoordinateForNode arguUpdateLanCoordinateForNode)
        {
            var data = new
            {
                arguUpdateLanCoordinateForNode.Node,
                arguUpdateLanCoordinateForNode.Segment,
                arguUpdateLanCoordinateForNode.Coord
            };
            QueryParameter queryParameter = null;
            if (!string.IsNullOrWhiteSpace(arguUpdateLanCoordinateForNode.DC))
            {
                queryParameter = new QueryParameter()
                {
                    Datacenter = arguUpdateLanCoordinateForNode.DC
                };
            }
            await ApiSendResponse(BuildCoordinatePath("update"), data, EnumConsulHttpMethod.Put, queryParameter);
        }
    }
}
